/*  
 * Copyright (C) 2011 Marta Spodymek
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *  
 */
package org.prometheuscode.web.feedback.spring.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.prometheuscode.web.feedback.ApplicationConfig;
import org.prometheuscode.web.feedback.binding.IBindingHolder;
import org.prometheuscode.web.feedback.binding.InputBinder;
import org.prometheuscode.web.feedback.domain.IFeed;
import org.prometheuscode.web.feedback.service.IFeedService;
import org.prometheuscode.web.feedback.validation.IValidator;
import org.prometheuscode.web.feedback.validation.IValidatorsManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

/**
 * Form handling controller.
 * 
 * @author marta
 * 
 */
@Controller
@RequestMapping("/user/{login}/*")
@SessionAttributes(value = { "inputs", "feed" })
public class FormController {

    private IValidatorsManager validatorsManager;

    private IFeedService feedService;

    private InputBinder binder;

    private ApplicationConfig appConfig;

    public FormController() {
    }

    /**
     * @return the appConfig
     */
    public ApplicationConfig getApplicationConfig() {
	return appConfig;
    }

    /**
     * @param appConfig
     *            the appConfig to set
     */
    @Autowired
    public void setApplicationConfig(ApplicationConfig appConfig) {
	this.appConfig = appConfig;
    }

    /*
     * Setters and getters
     */

    @Autowired
    public void setFeedService(IFeedService feedService) {
	this.feedService = feedService;

    }

    public IFeedService getFeedService() {
	return this.feedService;

    }

    @Autowired
    public void setnputBinder(InputBinder binder) {
	this.binder = binder;
    }

    public InputBinder getInputBinder() {
	return this.binder;
    }

    @Autowired
    public void setValidatorsManager(IValidatorsManager validatorsManager) {
	this.validatorsManager = validatorsManager;
    }

    public IValidatorsManager getValidatorsManager() {
	return this.validatorsManager;
    }

    /**
     * Setup the user form.
     * 
     * @param model
     * @param userLogin
     * @param type
     * @param feedId
     * @return
     */
    @RequestMapping(value = { "/form/{type}/{feedId}" }, method = RequestMethod.GET)
    public String setupForm(Model model,
	    @PathVariable("login") String userLogin,
	    @PathVariable("type") String type,
	    @PathVariable("feedId") String feedId) {

	/*
	 * Maybe save Feed data per user in Map if there are many questions it
	 * maybe be a problem with feed, or not. Average cookie holds 4Kb, UTF-8
	 * -> 1 char equals 1 byte. It would mean ~4000 characters
	 */

	/*
	 * TODO cache results here
	 */
	IFeed feed = this.feedService.getFeedWithData(feedId);

	Map<String, String> inputs = this.binder.bindInputs(feed);

	model.addAttribute("feed", feed);
	model.addAttribute("inputs", inputs);
	model.addAttribute(this.appConfig.getContentPageName(),
		this.appConfig.getFormPath(feedId));
	return this.appConfig.getMainTemplateName();
    }

    /**
     * Submit a form.
     * 
     * @param request
     * @param type
     * @param feedId
     * @param user
     * @param feed
     * @param model
     * @param status
     * @return
     */
    @RequestMapping(value = { "/form/{type}/{feedId}" }, method = RequestMethod.POST)
    public String submitForm(HttpServletRequest request,
	    @PathVariable("feedId") String feedId,
	    @ModelAttribute("feed") IFeed feed, Model model,
	    SessionStatus status) {

	IBindingHolder unbindedResult = this.binder.unbindInputs(request);

	IValidator validator = this.validatorsManager.getValidator(feedId);
	boolean isOk = validator.validate(unbindedResult.getInputs());
	if (!isOk) {
	    /* we have errors here */
	    model.addAttribute("error", validator.getErrors());
	    model.addAttribute(this.appConfig.getContentPageName(),
		    this.appConfig.getFormPath(feedId));
	    
	    return this.appConfig.getMainTemplateName();
	}
	
	/* commit the data */
	this.feedService.updateFormInputs(unbindedResult, feed);
	model.addAttribute(this.appConfig.getContentPageName(),
	    this.appConfig.getPagePath("success"));
	status.setComplete();
	/* TODO it should be redirect */
	return this.appConfig.getMainTemplateName();
	

    }

}